package udp_tcp.controller;


import udp_tcp.model.Message;
import udp_tcp.model.User;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class NetworkController {
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;
    private User currentUser;
    private List<User> connectedUsers = new ArrayList<>();

    public void startServer(int port, User user) throws IOException {
        currentUser = user;
        serverSocket = new ServerSocket(port);
        new Thread(this::acceptConnections).start();
    }

    public void connectToServer(String host, int port, User user) throws IOException {
        currentUser = user;
        clientSocket = new Socket(host, port);
        setupStreams();
    }

    private void acceptConnections() {
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(() -> handleClient(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket socket) {
        try {
            setupStreams(socket);
            User remoteUser = new User(in.readLine(), socket.getInetAddress().getHostAddress());
            connectedUsers.add(remoteUser);

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                Message message = new Message(remoteUser, inputLine);
                // 这里应该通知UI更新
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setupStreams() throws IOException {
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out.println(currentUser.getUsername()); // 发送用户名
    }

    private void setupStreams(Socket socket) throws IOException {
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void sendMessage(String content) {
        if (out != null) {
            out.println(content);
        }
    }

    public void disconnect() {
        try {
            if (serverSocket != null) serverSocket.close();
            if (clientSocket != null) clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}